package cl.sms;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import cl.webservice.WebserviceSms;
import cl.webservice.WebserviceUpdateSms;
import com.google.gson.Gson;

public class EnviarSms extends Activity 
{
	private Button btnVer;
	private WebserviceSms wsms = new WebserviceSms();
	private WebserviceUpdateSms wsups = new WebserviceUpdateSms();
	private int[] idsSms;
	private String datos;
	private String update = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);        
		btnVer = (Button) findViewById(R.id.botonVer);


		btnVer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				callwssms();
			}
		});

	}  


	/**
	 * Realiza la llamada al ws.
	 * @return void
	 */
	public void callwssms(){
		/**
		 * se llama al json del ws
		 */
		String datosJsonString = wsms.obtenerSms();
		Log.i("informacion",datosJsonString);

		if(!datosJsonString.equals("[]")){
			JSONArray jsonContent;
			try {
				jsonContent = new JSONArray(datosJsonString);
				int numItems = jsonContent.length();
				idsSms = new int[numItems];/*declaro un arreglo de id de sms*/
				
				datos = "";
				for (int i = 0; i < numItems; i++) {
					JSONObject item = jsonContent.getJSONObject(i);
					String numeroenvio = item.getString("numneroenvio");
					datos += "Numero Envio :"+numeroenvio;
					Log.i("numero",numeroenvio);
					String numerodestino = item.getString("numerodestino");
					datos += ";Numero Destino :"+numerodestino;
					Log.i("numero2",numerodestino);
					String mensaje = item.getString("mensaje");
					datos += "; Mensaje :"+mensaje+"\n\n";
					Log.i("mensaje",mensaje);
					/*Envia el mensaje*/
					sendSMS(numerodestino, mensaje);
					
					/*guarda el id del sms en un lista*/
					idsSms[i] = Integer.valueOf(item.getString("id"));
				}


				/**
				 * Para realizar el cambio de estado en la BD
				 */
				Gson gson = new Gson();
				String jsonIdSms = gson.toJson(idsSms);

				/**
				 * Envia los id al ws de actualizacion de estado
				 */
				update = wsups.updateSms(jsonIdSms);

				if(update.equals(1))
					Log.i("webserviceactualizacion","se actualizo");
				else
					Log.i("webserviceactualizacion","no se actualizo");

				Intent intent = new Intent(EnviarSms.this, MostrarSms.class);
				intent.putExtra("json", datosJsonString);
				intent.putExtra("datos", datos);
				datos = "";
				startActivity(intent);

				finish();


			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			Intent intent = new Intent(EnviarSms.this, MostrarSms.class);
			intent.putExtra("json", datosJsonString);
			intent.putExtra("datos", datos);
			startActivity(intent);
			finish();
		}
	}


	/**
	 * Realiza en envio de SMS
	 */
	private void sendSMS(String phoneNumber, String message)
	{        
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
				new Intent(SENT), 0);

		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
				new Intent(DELIVERED), 0);

		//---when the SMS has been sent---
		registerReceiver(new BroadcastReceiver(){
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "Enviando SMS ....", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(getBaseContext(), "Generic failure", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(getBaseContext(), "No service", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(getBaseContext(), "Null PDU", 
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(getBaseContext(), "Radio off", 
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(SENT));

		//---when the SMS has been delivered---
		registerReceiver(new BroadcastReceiver(){
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS delivered", 
							Toast.LENGTH_SHORT).show();
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(getBaseContext(), "SMS not delivered", 
							Toast.LENGTH_SHORT).show();
					break;                        
				}
			}
		}, new IntentFilter(DELIVERED));        

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
	}

	@Override
	public void onStop(){
		super.onStop();
		this.onDestroy();

	}


}